<template>
    <div class="admin-client-container">
        <div class="search-container">
            <el-input v-model="searchForm.id" type="number" placeholder="请输入ID" class="search-input" clearable />
            <el-input v-model="searchForm.clientName" placeholder="请输入应用名称" class="search-input" clearable />
            <el-select style="width: 100px;" v-model="searchForm.status" placeholder="请选择状态" @change="fetchTableData()">
                    <el-option label="全部" :value="null" />
                    <el-option label="等待审核" :value="1" />
                    <el-option label="审核通过" :value="2" />
                    <el-option label="审核未通过" :value="3" />
                </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>

        <el-table :data="tableData?.items" style="width: 100%" border stripe>
            <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip />
            <el-table-column prop="clientName" label="应用名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="scopes" label="授权权限" min-width="180" show-overflow-tooltip />
            <el-table-column prop="clientLogo" label="应用Logo" width="100">
                <template #default="{ row }">
                    <el-image :src="address.minioUrl+'image/'+row.clientLogo" :preview-src-list="[address.minioUrl+'image/'+row.clientLogo]" fit="cover"
                        class="client-logo" />
                </template>
            </el-table-column>
            <el-table-column prop="clientHostname" label="应用域名" min-width="150" show-overflow-tooltip />
            <el-table-column prop="userId" label="用户ID" min-width="100" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusText(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="failReason" label="失败原因" min-width="150" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="{ row }">
                    {{ formatDate(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180">
                <template #default="{ row }">
                    {{ formatDate(row.updateTime) }}
                </template>
            </el-table-column>

            <el-table-column prop="updateUser" label="上次更新员id" min-width="150" show-overflow-tooltip />

            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button 
                        v-if="row.status !== 2"
                        type="success" 
                        link 
                        @click="handleAudit(row, 2)"
                    >
                        通过
                    </el-button>
                    <el-button 
                        type="danger" 
                        link 
                        @click="openRejectDialog(row)"
                    >
                        拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination layout="prev, pager, next" v-model:current-page="searchForm.pageNo" :page-count="Number.parseInt(tableData?.page ?? '0')" @update:current-page="fetchTableData()" />
        </div>

        <!-- 拒绝原因对话框 -->
        <el-dialog
            v-model="rejectDialogVisible"
            title="拒绝原因"
            width="30%"
        >
            <el-form :model="rejectForm">
                <el-form-item label="拒绝原因" prop="failReason">
                    <el-input
                        v-model="rejectForm.failReason"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入拒绝原因（选填）"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="rejectDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmReject">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/base/request'
import AppInfo from '@/types/auth/AppInfo'
import Page from '@/base/page'
import GetAppInfoList from '@/types/auth/GetAppInfoList'
import { address } from '@/base/address'

// 搜索表单
const searchForm =ref<GetAppInfoList>({
    pageNo: 1,
    pageSize: 10,
})

// 表格数据
const tableData = ref<Page<AppInfo>>()

// 拒绝对话框相关
const rejectDialogVisible = ref(false)
const rejectForm = reactive({
    failReason: ''
})
const currentRow = ref<AppInfo | null>(null)

// 获取表格数据
const fetchTableData = async () => {
    try {
        const response = await request.post('/user/authClient/getAppInfoList',searchForm.value)
        if (response.data.code === 200) {
            tableData.value = response.data.data
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('获取数据失败')
    }
}

// 搜索
const handleSearch = () => {
    searchForm.value.pageNo = 1
    fetchTableData()
}
// 获取状态类型
const getStatusType = (status: number) => {
    switch (status) {
        case 1:
            return 'warning'
        case 2:
            return 'success'
        case 3:
            return 'danger'
        default:
            return 'info'
    }
}

// 获取状态文本
const getStatusText = (status: number) => {
    switch (status) {
        case 1:
            return '等待审核'
        case 2:
            return '审核通过'
        case 3:
            return '未通过'
        default:
            return '未知'
    }
}

// 打开拒绝对话框
const openRejectDialog = (row: AppInfo) => {
    currentRow.value = row
    rejectForm.failReason = ''
    rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
    if (!currentRow.value) return
    
    try {
        const response = await request.post('/user/authClient/audit', {
            id: currentRow.value.id,
            status: 3,
            failReason: rejectForm.failReason || ''
        })
        
        if (response.data.code === 200) {
            ElMessage.success('操作成功')
            rejectDialogVisible.value = false
            fetchTableData()
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 审核操作
const handleAudit = async (row: AppInfo, status: number) => {
    try {
        const response = await request.post('/user/authClient/audit', {
            id: row.id,
            status: status,
            failReason: ''
        })
        if (response.data.code === 200) {
            ElMessage.success('操作成功')
            fetchTableData()
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 格式化日期
const formatDate = (date: Date | string | undefined) => {
    if (!date) return '-'
    return new Date(date).toLocaleString()
}

onMounted(() => {
    fetchTableData()
})
</script>

<style scoped>
.admin-client-container {
    padding: 20px;
}

.search-container {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.search-input {
    width: 200px;
}

.client-logo {
    width: 40px;
    height: 40px;
    border-radius: 4px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>